--[[
    工具模块
    
    Author: mahaixing@gmail.com
    License: MIT
]]

local setmetatable = setmetatable
local cjson = require "cjson"
local cookie = require("resty.cookie"):new()

local _M = {
    _VERSION = "0.0.1"
}

function _M.get_cookie(key)
    return cookie:get(key)
end

function _M.is_null(val)
    return (val ~= nil and val ~= ngx.null and val ~= "" and val ~= " ") and false or true
end

function _M.log(msg, log_level)
    local customip = ngx.var.proxy_add_x_forwarded_for == nil
                    and ngx.var.remote_addr or ngx.var.proxy_add_x_forwarded_for
	local level = (log_level == nil) and ngx.INFO or log_level
    local log_msg = string.format("%s - %s %s %s %s %s", os.date("%Y-%m-%d %H:%M:%S"), ngx.var.request_uri, msg, ngx.var.server_addr, ngx.var.server_port, customip)
    ngx.log(level, log_msg)
end

function _M.get_url_args() 
    --抓取请求参数
    local args = {}
    if "GET" == ngx.var.request_method then
        args = ngx.req.get_uri_args()
    elseif "POST" == ngx.var.request_method then
        ngx.req.read_body()
        args = ngx.req.get_post_args()
    end
    
    return args
end

function _M.send_redirect(page_path, data)
	--判断Accept，当为json时，需返回json格式（注意：application/json和text/plain都要返回json）
	local accept = ngx.req.get_headers()["Accept"]
	if not isnull(accept) and (not isnull(string.find(accept, "application/json")) or not isnull(string.find(accept, "text/plain"))) then
		ngx.say(cjson.encode(data))
		ngx.exit(ngx.HTTP_OK)
	else
		ngx.redirect(pagePath)
	end
end

return _M